package store.lunangangster.engine.impl.entity.mgr;

import store.lunangangster.bpmn.model.FlowElement;
import store.lunangangster.engine.ProcessEngineConfiguration;
import store.lunangangster.engine.impl.auth.Authentication;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.HistoryEntity;

public class HistoryManager {

  protected ProcessEngineConfiguration processEngineConfiguration;
  protected HistoryEntityManager historyEntityManager;

  public HistoryManager(ProcessEngineConfiguration processEngineConfiguration) {
    this.processEngineConfiguration = processEngineConfiguration;
    this.historyEntityManager = processEngineConfiguration.getHistoryEntityManager();
  }

  public void createNewHistory(ExecutionEntity execution, FlowElement currentElement) {
    createNewHistory(execution, currentElement, null);
  }

  public void createNewHistory(ExecutionEntity execution, FlowElement currentElement, String notes) {
    HistoryEntity historyEntity = historyEntityManager.create();
    historyEntity.setProcessDefinitionId(execution.getProcessDefinitionId());
    historyEntity.setProcessDefinitionKey(execution.getProcessDefinitionKey());
    historyEntity.setProcessInstanceId(execution.getProcessInstanceId());
    historyEntity.setProcessInstanceName(execution.getProcessInstanceName());
    historyEntity.setParentScopeId(execution.getParentId());
    historyEntity.setParentScopeName(execution.getParent() == null ? null : execution.getParent().getName());
    if (currentElement == null) {
      currentElement = execution.getCurrentFlowElement();
    }
    if (currentElement != null) {
      historyEntity.setModelType(currentElement.getModelType());
      historyEntity.setModelId(currentElement.getId());
      historyEntity.setModelName(currentElement.getName());
    }
    historyEntity.setAuthentication(Authentication.getAuthentication());
    historyEntity.setNotes(notes);
    historyEntity.setTime(processEngineConfiguration.getEngineClock().now());

    historyEntityManager.insert(historyEntity);
  }
}
